/*
 * @Author: yxfan
 * @Date: 2023-09-05 11:08:00
 * @LastEditTime: 2023-09-05 14:52:09
 * @FilePath: /umi-demo/src/pages/demo/IndexDB/index.jsx
 * @Description:
 */
import { useEffect, useRef } from 'react';

export default () => {
    const db = useRef();

    useEffect(() => {
        openDB();
    }, []);

    function openDB() {
        var request = window.indexedDB.open('test', 1);
        request.onerror = function (event) {
            console.log('数据库打开报错');
        };
        request.onsuccess = function (event) {
            db.current = request.result;
            console.log('数据库打开成功');
        };

        request.onupgradeneeded = function (event) {
            db.current = event.target.result;
            var objectStore;
            if (!db.current.objectStoreNames.contains('person')) {
                objectStore = db.current.createObjectStore('person', {
                    keyPath: 'id',
                    autoIncrement: true,
                });
                objectStore.createIndex('nameIndex', 'name', { unique: false });
                objectStore.createIndex('emailIndex', 'email', {
                    unique: true,
                });

                // objectStore.add({ id: 2, name: '张三er', age: 18, email: 'xxxx' });
            }
        };
    }

    function add() {
        // 开启事务
        var transaction = db.current.transaction(['person'], 'readwrite');
        var objectStore = transaction.objectStore('person');
        var data = [
            { name: 'John Doe', age: 30 },
            { name: 'Jane Smith', age: 25 },
            { name: 'Bob Johnson', age: 40 },
        ];

        data.forEach(function (item) {
            var addRequest = objectStore.add(item);

            addRequest.onsuccess = function (event) {
                console.log('Added data with key:', addRequest.result);
            };
        });
    }

    function read() {
        var transaction = db.current.transaction(['person']);
        var objectStore = transaction.objectStore('person');
        var request = objectStore.get(1);

        request.onerror = function (event) {
            console.log('事务失败');
        };

        request.onsuccess = function (event) {
            if (request.result) {
                console.log('Name: ' + request.result.name);
                console.log('Age: ' + request.result.age);
                console.log('Email: ' + request.result.email);
            } else {
                console.log('未获得数据记录');
            }
        };
    }

    function readAll() {
        var transaction = db.current.transaction(['person']);
        var objectStore = transaction.objectStore('person');
        objectStore.openCursor().onsuccess = function (event) {
            var cursor = event.target.result;

            if (cursor) {
                console.log('Id: ' + cursor.key);
                // console.log('Name: ' + cursor.value.name);
                // console.log('Age: ' + cursor.value.age);
                cursor.continue();
            } else {
                console.log('没有更多数据了！');
            }
        };
    }

    function edit() {
        var transaction = db.current.transaction(['person'], 'readwrite');
        var objectStore = transaction.objectStore('person');
        var request = objectStore.put({ name: 'yxfan', id: 10 });
    }

    function find() {
        var transaction = db.current.transaction(['person']);
        var objectStore = transaction.objectStore('person');
        var index = objectStore.index('nameIndex');
        var request = index.get('yxfan');

        request.onsuccess = function (e) {
            var result = e.target.result;
            if (result) {
                console.log('通过索引找到了：', result);
                // ...
            } else {
                // ...
            }
        };
    }
    return (
        <div>
            <h2>Index DB</h2>
            <button onClick={add}>ADD</button>
            <button onClick={read}>READ</button>
            <button onClick={readAll}>READ ALL</button>
            <button onClick={edit}>EDIT</button>
            <button onClick={find}>FIND</button>
        </div>
    );
};
